<template>
  <div :class="[ 'hp-design-main-left', !sideState.isCollapse ? 'expand' : 'collapse' ]"
    ref="leftSiderbarRef">
    <el-scrollbar>
      <!-- 展开时 -->
      <div class="aside-expand "
        v-show="!sideState.isCollapse">
        <el-collapse class="left-collapse-panels"
          v-model="collapseState.active">
          <el-collapse-item v-for="(item, index) in sideState.panelGroups"
            :key="item.type"
            :name="item.type"
            :title="item.name">
            <draggable class="hp-panels"
              v-bind="{ name: `group-${index}`, pull: false, put: false ,sort:false}"
              :list="item.children"
              :item-key="item.type"
              @drag="onDrag"
              @end.stop.prevent="onDragEnd"
              ghost-class="draggable-ghost">
              <template #item="{ element: cItem }">
                <div class="hp-panels-item"
                  ref="itemExpandRef"
                  @click="hpDesigner.addLayoutItem(cItem)">
                  <div class="item-image">
                    <img :src="girdImageSrc(cItem)" />
                  </div>
                  <div class="item-title">
                    <span>{{ cItem.name }}</span>
                  </div>
                </div>
              </template>
            </draggable>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 收起时 -->
      <div class="aside-collapse"
        v-show="sideState.isCollapse">
        <draggable :list="sideState.allPanels"
          class="hp-panels-draggable"
          v-bind="{ pull: false, put: false ,sort: false,}"
          item-key="type"
          @drag="onDrag"
          @end.stop.prevent="onDragEnd"
          ghost-class="draggable-ghost">
          <template #item="{ element: cItem }">
            <div class="hp-panels-item"
              ref="itemCollapseRef"
              @click="hpDesigner.addLayoutItem(cItem)">
              <el-tooltip placement="right"
                :content="cItem.name"
                :hide-after="0">
                <div class="item-image">
                  <img :src="girdImageSrc(cItem)" />
                </div>
              </el-tooltip>
            </div>
          </template>
        </draggable>
      </div>
    </el-scrollbar>
    <div :class="[ 'hp-aside-toggle', 'left', sideState.isCollapse ? 'hidden' : '' ]"
      @click="sideState.isCollapse = !sideState.isCollapse">
      <el-icon class="toggle-icon">
        <CaretLeft v-show="!sideState.isCollapse" />
        <CaretRight v-show="sideState.isCollapse" />
      </el-icon>
    </div>
  </div>
</template>

<script setup>
import { inject, onMounted, reactive, ref } from 'vue';
import { CaretLeft, CaretRight } from '@element-plus/icons-vue';
import draggable from 'vuedraggable';
import { getImage } from '@hp/assets/index.js';
import { pluginManager } from '@hp/utils/pluginManager.js';
import { deepClone, getUUID } from '@hp/utils/data.js';
const hpDesigner = inject('hpDesigner');
const layoutAttrs = inject('layoutAttrs');
const { state } = hpDesigner;

// 侧边的数据集
const sideState = reactive({
  // 所有面板
  allPanels: [],
  // 面板分组
  panelGroups: [],
  // 是否收起
  isCollapse: true,
});

// 折叠组件的数据集
const collapseState = reactive({
  active: ['base', 'chart', 'system']
});
/**
 * 获取面板的图标图片
 * 
 * @param panelItem 面板信息
 */
const girdImageSrc = (panelItem) => {
  return getImage(panelItem.icon);
};

// 引用左侧栏元素
const leftSiderbarRef = ref(null);
// 获取item收起的ref
const itemCollapseRef = ref('')
// 获取item展开的ref
const itemExpandRef = ref('')
// 拖拽方法
const onDrag = (event) => {
  event.preventDefault();
  const leftSiderbarWidth = leftSiderbarRef.value.offsetWidth;
  const dragEndX = event.clientX;
  // 判断是否在左侧栏外部
  if (dragEndX > leftSiderbarWidth) {
    createPlaceholder(event)
  } else {
    // 如果在左侧栏内部，移除占位符
    removePlaceholder()
  }
};
// 创建遮罩
const createPlaceholder = (event) => {
  const placeholder = document.getElementById('drag-placeholder');

  // 如果占位符不存在，则创建
  if (!placeholder) {
    const placeholderElement = document.createElement('div');
    placeholderElement.id = 'drag-placeholder';
    placeholderElement.style.position = 'absolute';
    placeholderElement.style.backgroundColor = '#fdd';
    placeholderElement.style.border = '1px dashed #ccc';
    placeholderElement.style.width = '120px'; // 根据你的需求设置宽度
    placeholderElement.style.height = '60px'; // 根据你的需求设置高度
    placeholderElement.style.zIndex = 99999999;
    placeholderElement.style.pointerEvents = 'none'; // 防止占位符干扰鼠标事件
    document.body.appendChild(placeholderElement);
  }
  const itemW = sideState.isCollapse ? itemCollapseRef.value.clientWidth : itemExpandRef.value[0].clientWidth;
  // 更新占位符的位置，考虑左侧栏宽度和页面滚动偏移量
  const placeholderElement = document.getElementById('drag-placeholder');
  placeholderElement.style.left = `${event.clientX - itemW * 0.5}px`;
  placeholderElement.style.top = `${event.clientY + 10}px`;
}
// 移除遮罩
const removePlaceholder = () => {
  const placeholder = document.getElementById('drag-placeholder');
  if (placeholder) {
    placeholder.remove();
  }
};

// 拖拽结束
const onDragEnd = (event) => {
  removePlaceholder()
  if (event.item) {
    const rect = event.item.getBoundingClientRect();
    const leftSiderbarWidth = leftSiderbarRef.value.offsetWidth;
    // 左侧栏宽度 (如果有菜单栏)
    // var element = document.querySelector('.layout-aside');
    // const asideW = element ? element.getBoundingClientRect().width : 0;
    // const dragEndX = event.originalEvent.clientX - asideW;
    const dragEndX = event.originalEvent.clientX;
    if (dragEndX > leftSiderbarWidth) {
      const movedItem = deepClone(event.item.__draggable_context.element);
      movedItem.x = rect.x;
      movedItem.y = rect.y;
      hpDesigner.addLayoutItem(movedItem);
    }
  }
};
onMounted(() => {
  setTimeout(() => {
    let panels = [];
    sideState.panelGroups = pluginManager.getPanelGroupValues();
    sideState.panelGroups.forEach(item => panels = [...panels, ...item.children]);
    sideState.allPanels = panels;
  }, 300);
});
</script>

<style lang="scss" scoped>
$border: 1px solid #d9d9d9;

.hp-design-main-left {
	position: relative;
	height: 100%;
	width: 240px;
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	border-right: $border;
	transition: all 0.3s;
	&.collapse {
		width: 60px;
	}
	:deep(.el-collapse-item__header) {
		--el-collapse-header-height: 38px;
		padding-left: 8px;
		background-color: rgba(0, 0, 0, 0.02);
		border-bottom: $border;
	}
	:deep(.el-collapse-item__wrap) {
		padding: 8px;
		border-bottom: $border;
		.el-collapse-item__content {
			padding-bottom: 0;
		}
	}
}

.left-collapse-panels {
	border-top: none;
}

.aside-expand {
	.hp-panels {
		display: grid;
		gap: 15px 15px;
		grid-template-columns: repeat(2, minmax(20px, 1fr));
		&-item {
			position: relative;
			background: #fff;
			height: 80px;
			display: flex;
			flex-direction: column;
			border-radius: 4px;
			border: $border;
			cursor: pointer;
			&:hover {
				border-color: #409eff;
				.item-title {
					border-color: #409eff;
				}
			}

			.item-image {
				flex: 1;
				min-height: 10px;
				text-align: center;
				padding: 5px;
				img {
					height: 100%;
				}
			}
			.item-title {
				padding: 0 5px;
				border-top: $border;
				text-align: center;
			}
		}
	}
}

.aside-collapse {
	overflow: hidden;
	.hp-panels {
		display: block;
		&-draggable {
			padding: 5px;
		}
		&-item {
			position: relative;
			cursor: pointer;
			background: #fff;
			height: 50px;
			display: flex;
			flex-direction: column;
			margin-bottom: 8px;
			.item-image {
				flex: 1;
				min-height: 10px;
				text-align: center;
				padding: 5px;
				border-radius: 4px;
				border: $border;
				&:hover {
					border-color: #409eff;
				}
				img {
					height: 100%;
				}
			}
		}
	}
}

.draggable-ghost {
	opacity: 0.5 !important;
	background-color: #f0f0f0 !important;
	border: 1px solid #d9d9d9 !important;
	border-radius: 4px !important;
}
.hp-panels-item:hover:after {
	position: absolute;
	top: 0;
	right: 0;
	content: '+';
	color: white;
	background-color: red;
	display: inline-block;
	width: 20px;
	height: 20px;
	line-height: 17px;
	text-align: center;
	border-radius: 50%;
	font-weight: bold;
}
</style>
